<template>
  <div class="quotation-record">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="客户代码">
          <el-input v-model="searchForm.customerCode" placeholder="请输入客户代码" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="业务员">
          <el-select v-model="searchForm.salesperson" placeholder="请选择业务员" clearable style="width: 150px">
                            <el-option v-for="emp in employees" :key="emp.employeeCode" :label="emp.employeeName" :value="emp.employeeName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="草稿"/>
            <el-option label="已提交" value="已提交"/>
            <el-option label="已生成合同" value="已生成合同"/>
            <el-option label="合同审核通过" value="合同审核通过"/>
            <el-option label="外发加工中" value="外发加工中"/>
            <el-option label="已入库" value="已入库"/>
            <el-option label="合同审核拒绝" value="合同审核拒绝"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否含税">
          <el-select v-model="searchForm.isTaxIncluded" placeholder="请选择" clearable style="width: 120px">
            <el-option label="否" :value="false"/>
            <el-option label="是" :value="true"/>
          </el-select>
        </el-form-item>
        <el-form-item label="订单日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增报价单</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="quotationNo" label="报价单号" width="150" fixed="left"/>
        <el-table-column prop="customerCode" label="客户代码" width="120"/>
        <el-table-column prop="customerName" label="客户名称" width="180" show-overflow-tooltip/>
        <el-table-column prop="salesperson" label="业务员" width="100"/>
        <el-table-column prop="contractNo" label="合同编号" width="150" show-overflow-tooltip/>
        <el-table-column prop="orderDate" label="订单日期" width="110"/>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否含税" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isTaxIncluded ? 'success' : 'info'" size="small">
              {{ scope.row.isTaxIncluded ? '含税' : '不含税' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="付款方式" width="120"/>
        <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
          <template #default="scope">
            ¥{{ (scope.row.totalAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalTaxAmount" label="含税总金额" width="130" align="right">
          <template #default="scope">
            ¥{{ (scope.row.totalTaxAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdBy" label="创建人" width="100"/>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip/>
        <el-table-column label="操作" width="380" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)" 
                       :disabled="!canEdit(scope.row.status)">
              编辑
            </el-button>
            <el-button link type="warning" size="small" @click="handleSubmit(scope.row)"
                       :disabled="!canSubmit(scope.row.status)">
              提交
            </el-button>
            <el-button link type="success" size="small" @click="handleGenerateContract(scope.row)"
                       :disabled="!canGenerateContract(scope.row.status)">
              生成合同
            </el-button>
            <el-button link type="info" size="small" @click="handleOutsourcing(scope.row)"
                       :disabled="!canOutsource(scope.row.status)">
              外发加工
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
                       :disabled="!canDelete(scope.row.status)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="报价单详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <QuotationDetail v-if="detailDialogVisible" :quotation-id="currentQuotationId" @close="detailDialogVisible = false"/>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑报价单"
      width="95%"
      :close-on-click-modal="false"
    >
      <QuotationEdit v-if="editDialogVisible" :quotation-id="currentQuotationId" @close="handleEditClose"/>
    </el-dialog>

    <!-- 外发加工弹窗 -->
    <el-dialog
      v-model="outsourcingDialogVisible"
      title="新增外发单"
      width="1200px"
      :close-on-click-modal="false"
      :before-close="handleOutsourcingDialogClose"
    >
      <div class="outsourcing-creation">
        <div class="quotation-info-bar" style="background: #f5f7fa; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
          <span><strong>已选报价单：</strong>{{ currentQuotation?.quotationNo }} - {{ currentQuotation?.customerName }}</span>
        </div>

        <h4>选择物料和供应商</h4>
        <el-form
          ref="outsourcingFormRef"
          :model="outsourcingForm"
          :rules="outsourcingRules"
          label-width="120px"
          size="default"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物料明细" prop="quotationItemId">
                <el-select
                  v-model="outsourcingForm.quotationItemId"
                  placeholder="请选择物料明细"
                  style="width: 100%"
                  @change="handleItemSelect"
                >
                  <el-option
                    v-for="item in currentQuotation?.items || []"
                    :key="item.id"
                    :label="`${item.productName} (${item.materialCode || '无编码'}) - 数量: ${item.quantity}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierCode">
                <el-select
                  v-model="outsourcingForm.supplierCode"
                  placeholder="请选择供应商"
                  style="width: 100%"
                  filterable
                  allow-create
                  @change="handleSupplierChange"
                >
                  <el-option
                    v-for="supplier in supplierOptions"
                    :key="supplier.supplierCode"
                    :label="`${supplier.supplierCode} - ${supplier.supplierName}`"
                    :value="supplier.supplierCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input
                  v-model="outsourcingForm.supplierName"
                  placeholder="请输入供应商名称"
                  @blur="handleSupplierNameChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称">
                <el-input
                  v-model="outsourcingForm.productName"
                  placeholder="自动填充"
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="外发数量" prop="quantity">
                <el-input
                  v-model.number="outsourcingForm.quantity"
                  placeholder="请输入外发数量"
                  style="width: 100%"
                  @input="handleQuantityInput"
                  @blur="calculateTotalAmount"
                >
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发单价">
                <el-input
                  v-model.number="outsourcingForm.unitPrice"
                  placeholder="请输入外发单价"
                  style="width: 100%"
                  @input="handleUnitPriceInput"
                  @blur="calculateTotalAmount"
                >
                  <template #suffix>
                    <span style="color: #999;">元</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发总金额">
                <el-input
                  v-model.number="outsourcingForm.totalAmount"
                  placeholder="自动计算"
                  style="width: 100%"
                  readonly
                >
                  <template #suffix>
                    <span style="color: #999;">元</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="外发日期" prop="outsourcingDate">
                <el-date-picker
                  v-model="outsourcingForm.outsourcingDate"
                  type="date"
                  placeholder="选择外发日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计回厂日期">
                <el-date-picker
                  v-model="outsourcingForm.expectedReturnDate"
                  type="date"
                  placeholder="选择预计回厂日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注">
            <el-input
              v-model="outsourcingForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="outsourcingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOutsourcing" :loading="outsourcingLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { quotationAPI, outsourcingAPI, supplierAPI, employeeAPI } from '../utils/api'
import QuotationDetail from './QuotationDetail.vue'
import QuotationEdit from './QuotationEdit.vue'

export default {
  name: 'QuotationRecord',
  components: {
    QuotationDetail,
    QuotationEdit
  },
  setup() {
    const router = useRouter()
    // 响应式数据
    const loading = ref(false)
    const tableData = ref([])
    const multipleSelection = ref([])
    const employees = ref([])
    const dateRange = ref([])
    
    // 弹窗状态
    const detailDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const outsourcingDialogVisible = ref(false)
    const currentQuotationId = ref(null)
    const currentQuotation = ref(null)
    const outsourcingLoading = ref(false)
    const outsourcingFormRef = ref(null)
    const supplierOptions = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      salesperson: '',
      contractNo: '',
      status: '',
      isTaxIncluded: null,
      startDate: '',
      endDate: '',
      paymentMethod: '',
      createdBy: ''
    })
    
    // 分页数据
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 外发加工表单
    const outsourcingForm = reactive({
      quotationId: null,
      quotationItemId: null,
      supplierCode: '',
      supplierName: '',
      materialCode: '',
      productName: '',
      quantity: 1,
      unitPrice: null,
      totalAmount: 0,
      outsourcingDate: '',
      expectedReturnDate: '',
      remark: ''
    })

    // 外发加工表单验证规则
    const outsourcingRules = reactive({
      quotationItemId: [
        { required: true, message: '请选择物料明细', trigger: 'change' }
      ],
      supplierCode: [
        { required: true, message: '请选择或输入供应商代码', trigger: 'change' }
      ],
      supplierName: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入外发数量', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            const num = Number(value)
            if (!num || num <= 0 || !Number.isInteger(num)) {
              callback(new Error('外发数量必须为正整数'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      unitPrice: [
        { 
          validator: (rule, value, callback) => {
            if (value !== undefined && value !== null && value !== '') {
              const num = Number(value)
              if (isNaN(num) || num < 0) {
                callback(new Error('外发单价必须为非负数'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      outsourcingDate: [
        { required: true, message: '请选择外发日期', trigger: 'change' }
      ]
    })
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '草稿': return 'info'
        case '已提交': return 'primary'
        case '已生成合同': return 'warning'
        case '合同审核通过': return 'success'
        case '外发加工中': return ''
        case '已入库': return 'success'
        case '合同审核拒绝': return 'danger'
        default: return 'info'
      }
    }

    // 判断是否可以编辑
    const canEdit = (status) => {
      // 在合同被审核之前，均可以编辑报价单
      return status === '草稿' || status === '已提交' || status === '已生成合同'
    }

    // 判断是否可以提交
    const canSubmit = (status) => {
      return status === '草稿'
    }

    // 判断是否可以生成合同
    const canGenerateContract = (status) => {
      // 在合同被审核之前，均可以重新生成合同
      return status === '已提交' || status === '已生成合同'
    }

    // 判断是否可以外发加工
    const canOutsource = (status) => {
      // 合同审核通过后都可以外发加工，包括外发加工中和已入库状态
      // 因为一个报价单有多个物料，可能需要多次外发加工
      return status === '合同审核通过' || status === '外发加工中' || status === '已入库'
    }

    // 判断是否可以删除
    const canDelete = (status) => {
      // 各种状态均可以直接删除
      return true
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    // 处理日期范围变化
    const handleDateRangeChange = (dates) => {
      if (dates && dates.length === 2) {
        searchForm.startDate = dates[0]
        searchForm.endDate = dates[1]
      } else {
        searchForm.startDate = ''
        searchForm.endDate = ''
      }
    }
    
    // 加载数据
    const loadData = async () => {
      try {
        loading.value = true
        const params = {
          current: pagination.current,
          size: pagination.size,
          ...searchForm
        }
        
        const response = await quotationAPI.getQuotationPage(params)
        if (response.code === 200) {
          tableData.value = response.data.records
          pagination.total = response.data.total
        }
      } catch (error) {
        console.error('加载报价单列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取业务员选项
    const fetchEmployees = async () => {
      try {
        const response = await employeeAPI.getAllEmployees()
        if (response.code === 200) {
          employees.value = response.data
        }
      } catch (error) {
        console.error('获取业务员列表失败:', error)
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadData()
    }
    
    // 重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'isTaxIncluded') {
          searchForm[key] = null
        } else {
          searchForm[key] = ''
        }
      })
      dateRange.value = []
      pagination.current = 1
      loadData()
    }
    
    // 新增
    const handleAdd = () => {
      // 跳转到报价单新增页面
      window.open('/quotation', '_blank')
    }
    
    // 查看详情
    const handleView = (row) => {
      currentQuotationId.value = row.id
      detailDialogVisible.value = true
    }
    
    // 编辑
    const handleEdit = (row) => {
      // 检查状态，在合同被审核之前都可以编辑
      if (!canEdit(row.status)) {
        ElMessage.warning('合同已审核，无法编辑报价单')
        return
      }
      
      currentQuotationId.value = row.id
      editDialogVisible.value = true
    }
    
    // 编辑关闭回调
    const handleEditClose = (needRefresh) => {
      editDialogVisible.value = false
      if (needRefresh) {
        loadData()
      }
    }
    
    // 删除
    const handleDelete = async (row) => {
      try {
        let confirmMessage = `确认删除报价单 "${row.quotationNo}" 吗？`
        let warningMessage = ''
        
        // 根据不同状态给出不同的警告信息
        if (row.status === '已生成合同' || row.status === 'CONTRACT_GENERATED') {
          warningMessage = '删除报价单将同时删除相关合同'
        } else if (row.status === '外发加工中') {
          warningMessage = '删除报价单将影响正在进行的外发加工'
        } else if (row.status === '已入库') {
          warningMessage = '删除报价单将影响已入库的物料记录'
        }
        
        if (warningMessage) {
          confirmMessage = `报价单 "${row.quotationNo}" 当前状态为"${row.status}"。\n\n${warningMessage}，确认继续删除吗？`
        }
        
        await ElMessageBox.confirm(confirmMessage, '删除确认', {
          type: 'warning',
          confirmButtonText: '确认删除',
          cancelButtonText: '取消'
        })
        
        const response = await quotationAPI.deleteQuotation(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除报价单失败:', error)
          ElMessage.error('删除失败，请稍后重试')
        }
      }
    }
    
    // 批量删除
    const handleBatchDelete = async () => {
      try {
        // 统计不同状态的报价单数量
        const contractItems = multipleSelection.value.filter(row => 
          row.status === '已生成合同' || row.status === 'CONTRACT_GENERATED'
        )
        const outsourcingItems = multipleSelection.value.filter(row => 
          row.status === '外发加工中'
        )
        const warehousedItems = multipleSelection.value.filter(row => 
          row.status === '已入库'
        )
        
        let confirmMessage = `确认删除选中的 ${multipleSelection.value.length} 条报价单吗？`
        let warnings = []
        
        if (contractItems.length > 0) {
          warnings.push(`${contractItems.length} 条已生成合同的记录将同时删除相关合同`)
        }
        if (outsourcingItems.length > 0) {
          warnings.push(`${outsourcingItems.length} 条外发加工中的记录将影响正在进行的外发加工`)
        }
        if (warehousedItems.length > 0) {
          warnings.push(`${warehousedItems.length} 条已入库的记录将影响已入库的物料记录`)
        }
        
        if (warnings.length > 0) {
          confirmMessage = `批量删除包含以下影响：\n\n${warnings.join('\n')}\n\n确认继续删除吗？`
        }
        
        await ElMessageBox.confirm(confirmMessage, '批量删除确认', {
          type: 'warning',
          confirmButtonText: '确认删除',
          cancelButtonText: '取消'
        })
        
        const deletePromises = multipleSelection.value.map(row => 
          quotationAPI.deleteQuotation(row.id)
        )
        
        await Promise.all(deletePromises)
        ElMessage.success('批量删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败，请稍后重试')
        }
      }
    }
    
    // 提交报价单
    const handleSubmit = async (row) => {
      try {
        await ElMessageBox.confirm(`确认提交报价单 "${row.quotationNo}" 吗？`, '提示', {
          type: 'warning'
        })
        
        const response = await quotationAPI.submitQuotation(row.id)
        if (response.code === 200) {
          ElMessage.success('提交成功')
          loadData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交报价单失败:', error)
        }
      }
    }
    
    // 生成合同
    const handleGenerateContract = async (row) => {
      try {
        // 检查报价单状态
        if (!canGenerateContract(row.status)) {
          ElMessage.warning('当前状态不允许生成合同')
          return
        }
        
        let confirmMessage = `确认为报价单 "${row.quotationNo}" 生成合同吗？`
        let confirmTitle = '生成合同确认'
        
        // 如果已经生成过合同，提示会重新生成
        if (row.status === '已生成合同' || row.status === 'CONTRACT_GENERATED') {
          confirmMessage = `报价单 "${row.quotationNo}" 已存在合同。\n\n重新生成合同将替换原有合同，确认继续吗？`
          confirmTitle = '重新生成合同确认'
        }
        
        await ElMessageBox.confirm(
          confirmMessage, 
          confirmTitle, 
          {
            type: 'warning',
            confirmButtonText: '确认生成',
            cancelButtonText: '取消'
          }
        )
        
        loading.value = true
        const response = await quotationAPI.generateContract(row.id)
        
        if (response.code === 200) {
          const successMessage = row.status === '已生成合同' || row.status === 'CONTRACT_GENERATED' 
            ? '合同重新生成成功！您可以前往合同审核页面查看和下载新合同。'
            : '合同生成成功！您可以前往合同审核页面查看和下载合同。'
          
          ElMessage.success(successMessage)
          loadData() // 刷新列表
          
          // 询问是否跳转到合同审核页面
          setTimeout(async () => {
            try {
              await ElMessageBox.confirm('是否立即跳转到合同审核页面查看合同？', '提示', {
                type: 'info',
                confirmButtonText: '立即查看',
                cancelButtonText: '稍后查看'
              })
              // 这里可以添加路由跳转逻辑
              router.push('/contract-audit')
            } catch (e) {
              // 用户选择稍后查看，不做处理
            }
          }, 1000)
        } else {
          ElMessage.error(response.message || '合同生成失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('生成合同失败:', error)
          ElMessage.error('生成合同失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 选择变化
    const handleSelectionChange = (selection) => {
      multipleSelection.value = selection
    }
    
    // 页码变化
    const handleCurrentChange = (page) => {
      pagination.current = page
      loadData()
    }
    
    // 页大小变化
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      loadData()
    }

    // 外发加工按钮点击
    const handleOutsourcing = async (row) => {
      try {
        // 获取报价单详情
        const response = await quotationAPI.getQuotationById(row.id)
        if (response.code === 200) {
          currentQuotation.value = response.data
          
          // 重置外发表单
          resetOutsourcingForm()
          
          // 设置基础信息
          outsourcingForm.quotationId = row.id
          outsourcingForm.outsourcingDate = new Date().toISOString().split('T')[0] // 默认今天
          
          // 如果有物料明细，预填第一个
          if (response.data.items && response.data.items.length > 0) {
            const firstItem = response.data.items[0]
            outsourcingForm.quotationItemId = firstItem.id
            outsourcingForm.productName = firstItem.productName || ''
            outsourcingForm.materialCode = firstItem.materialCode || ''
            outsourcingForm.quantity = firstItem.quantity || 1
          }
          
          // 加载供应商选项
          await loadSupplierOptions()
          
          outsourcingDialogVisible.value = true
        }
      } catch (error) {
        console.error('获取报价单详情失败:', error)
        ElMessage.error('获取报价单信息失败')
      }
    }

    // 重置外发加工表单
    const resetOutsourcingForm = () => {
      Object.keys(outsourcingForm).forEach(key => {
        if (key === 'quantity') {
          outsourcingForm[key] = 1
        } else if (key === 'totalAmount') {
          outsourcingForm[key] = 0
        } else {
          outsourcingForm[key] = key.includes('Id') ? null : ''
        }
      })
    }

    // 处理外发数量输入
    const onOutsourcingQuantityChange = (value) => {
      if (value === '') {
        outsourcingForm.quantity = null
      } else {
        outsourcingForm.quantity = Number(value)
      }
      calculateOutsourcingTotal()
    }

    // 处理外发单价输入
    const onOutsourcingPriceChange = (value) => {
      if (value === '') {
        outsourcingForm.unitPrice = null
      } else {
        outsourcingForm.unitPrice = Number(value)
      }
      calculateOutsourcingTotal()
    }

    // 格式化外发数量和单价
    const formatOutsourcingNumber = (field, isPrice = false) => {
      if (outsourcingForm[field] === null || outsourcingForm[field] === '') {
        outsourcingForm[field] = null
      } else {
        outsourcingForm[field] = Number(outsourcingForm[field])
      }
      // 重新计算总金额
      calculateOutsourcingTotal()
    }

    // 加载供应商选项
    const loadSupplierOptions = async () => {
      try {
        const response = await supplierAPI.getAllSuppliers()
        if (response.code === 200) {
          supplierOptions.value = response.data
        }
      } catch (error) {
        console.error('获取供应商选项失败:', error)
      }
    }

    // 供应商代码选择变化
    const handleSupplierChange = (supplierCode) => {
      const supplier = supplierOptions.value.find(s => s.supplierCode === supplierCode)
      if (supplier) {
        outsourcingForm.supplierName = supplier.supplierName
      }
    }

    // 供应商名称选择变化
    const handleSupplierNameChange = (supplierName) => {
      const supplier = supplierOptions.value.find(s => s.supplierName === supplierName)
      if (supplier) {
        outsourcingForm.supplierCode = supplier.supplierCode
      }
    }

    // 计算外发总金额
    const calculateOutsourcingTotal = () => {
      if (outsourcingForm.quantity && outsourcingForm.unitPrice) {
        outsourcingForm.totalAmount = Number((outsourcingForm.quantity * outsourcingForm.unitPrice).toFixed(2))
      } else {
        outsourcingForm.totalAmount = 0
      }
    }

    // 物料明细选择变化
    const handleItemSelect = (itemId) => {
      if (!currentQuotation.value || !currentQuotation.value.items) return
      
      const selectedItem = currentQuotation.value.items.find(item => item.id === itemId)
      if (selectedItem) {
        outsourcingForm.productName = selectedItem.productName || ''
        outsourcingForm.materialCode = selectedItem.materialCode || ''
        outsourcingForm.quantity = selectedItem.quantity || 1
        // 清空价格相关字段，需要手动输入
        outsourcingForm.unitPrice = 0
        outsourcingForm.totalAmount = 0
      }
    }

    // 处理数量输入
    const handleQuantityInput = (value) => {
      const num = Number(value)
      if (!isNaN(num) && num >= 0) {
        outsourcingForm.quantity = num
      }
    }

    // 处理单价输入
    const handleUnitPriceInput = (value) => {
      const num = Number(value)
      if (!isNaN(num) && num >= 0) {
        outsourcingForm.unitPrice = num
      }
    }

    // 计算总金额
    const calculateTotalAmount = () => {
      // 自动计算总金额：数量 × 单价
      const quantity = Number(outsourcingForm.quantity) || 0
      const unitPrice = Number(outsourcingForm.unitPrice) || 0
      
      if (quantity > 0 && unitPrice > 0) {
        outsourcingForm.totalAmount = Math.round(quantity * unitPrice * 100) / 100  // 保留2位小数
      } else if (quantity === 0 || unitPrice === 0) {
        outsourcingForm.totalAmount = 0
      }
    }

    // 处理外发加工弹窗关闭
    const handleOutsourcingDialogClose = () => {
      resetOutsourcingForm()
      outsourcingDialogVisible.value = false
    }

    // 创建外发单
    const handleCreateOutsourcing = async () => {
      try {
        await outsourcingFormRef.value.validate()
        outsourcingLoading.value = true
        
        // 准备提交数据，确保数字类型正确
        const submitData = {
          ...outsourcingForm,
          quantity: Number(outsourcingForm.quantity) || 0,
          unitPrice: Number(outsourcingForm.unitPrice) || 0,
          totalAmount: Number(outsourcingForm.totalAmount) || 0,
          createdBy: 'admin' // 实际应用中应该从用户信息获取
        }
        
        // 验证必要字段
        if (submitData.quantity <= 0) {
          ElMessage.error('外发数量必须大于0')
          return
        }
        
        const response = await outsourcingAPI.createOutsourcing(submitData)
        if (response.code === 200) {
          ElMessage.success('外发单创建成功')
          outsourcingDialogVisible.value = false
          resetOutsourcingForm()
          
          // 询问是否跳转到外发加工管理页面
          setTimeout(async () => {
            try {
              await ElMessageBox.confirm('是否立即跳转到外发加工管理页面查看？', '提示', {
                type: 'info',
                confirmButtonText: '立即查看',
                cancelButtonText: '稍后查看'
              })
              router.push('/outsourcing')
            } catch (e) {
              // 用户选择稍后查看，不做处理
            }
          }, 1000)
        }
      } catch (error) {
        if (error.message !== 'Validation failed') {
          console.error('创建外发单失败:', error)
          ElMessage.error('创建外发单失败：' + (error.response?.data?.message || error.message))
        }
      } finally {
        outsourcingLoading.value = false
      }
    }
    
    // 组件挂载
    onMounted(() => {
      fetchEmployees()
      loadData()
      loadSupplierOptions()
    })
    
    return {
      loading,
      tableData,
      multipleSelection,
      employees,
      dateRange,
      detailDialogVisible,
      editDialogVisible,
      outsourcingDialogVisible,
      currentQuotationId,
      currentQuotation,
      outsourcingLoading,
      outsourcingFormRef,
      supplierOptions,
      outsourcingForm,
      outsourcingRules,
      searchForm,
      pagination,
      getStatusTagType,
      canEdit,
      canSubmit,
      canGenerateContract,
      canOutsource,
      canDelete,
      formatDate,
      handleDateRangeChange,
      loadData,
      handleSearch,
      handleReset,
      handleAdd,
      handleView,
      handleEdit,
      handleEditClose,
      handleDelete,
      handleBatchDelete,
      handleSubmit,
      handleGenerateContract,
      handleOutsourcing,
      loadSupplierOptions,
      handleSupplierChange,
      handleSupplierNameChange,
      calculateOutsourcingTotal,
      handleCreateOutsourcing,
      handleItemSelect,
      handleQuantityInput,
      handleUnitPriceInput,
      calculateTotalAmount,
      handleOutsourcingDialogClose,
      handleSelectionChange,
      handleCurrentChange,
      handleSizeChange,
      onOutsourcingQuantityChange,
      onOutsourcingPriceChange,
      formatOutsourcingNumber
    }
  }
}
</script>

<style scoped>
.quotation-record {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .el-button--small) {
  margin: 0 2px;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

.info-card {
  margin-bottom: 0;
}

.info-card :deep(.el-card__header) {
  background-color: #f5f7fa;
  padding: 10px 20px;
}

.form-card :deep(.el-card__header) {
  background-color: #f0f9ff;
  padding: 10px 20px;
}

.info-card :deep(.el-card__body),
.form-card :deep(.el-card__body) {
  padding: 20px;
}
</style> 